package org.deng.vertx.common.util;

import java.time.LocalDate;

/**
 * @author 邓力宾
 * @date 2021/7/6 13:54
 * @desc 身份证号工具类
 */
public class IdCardUtils {
    private IdCardUtils(){}
    private static final int INVALID_AGE = -1;//非法的年龄，用于处理异常。


    /**
     * 获取性别
     * @param idNumber
     * @return 0:未知 1：男 2：女
     */
    public static int getGenderByIdNumber(String idNumber) {
        if(idNumber == null || idNumber.length() != 18){
            return 0; //未知
        }
        int gender = Integer.parseInt(idNumber.substring(16, 17));
        if(gender % 2 == 0){
            return 2;
        }
        return 1;
    }
    /**
     *根据身份证号码计算年龄
     * idNumber 考虑到了15位身份证，但不一定存在
     */
    public static int getAgeByIdNumber(String idNumber) {
        if(idNumber == null || idNumber.isEmpty()){
            return INVALID_AGE;
        }
        String dateStr;
        if (idNumber.length() == 15) {
            dateStr = "19" + idNumber.substring(6, 12);
        } else if (idNumber.length() == 18) {
            dateStr = idNumber.substring(6, 14);
        } else {//默认是合法身份证号，但不排除有意外发生
            return INVALID_AGE;
        }

        try{
            LocalDate birthday = DateUtils.parseLocalDate(dateStr, "yyyyMMdd");

            LocalDate now = LocalDate.now();
            return (int)DateUtils.calculateYears(birthday, now);
        }catch (Exception e){
            return INVALID_AGE;
        }

    }

    public static void main(String[] args){
        // int age = getAgeByIdNumber("511602199107200512");
        // System.out.println(age);
    }

}
